﻿/**************************************************************
 *
 * 唯一标识：36bb593a-fc93-4a45-93f4-7c41318bd4bd
 * 命名空间：Sgr.UPMS.Application.Commands.Users
 * 创建时间：2023/8/27 11:34:55
 * 机器名称：DESKTOP-S0D075D
 * 创建者：antho
 * 电子邮箱：fengqinhua2016@163.com
 * 描述：修改用户状态命令处理器
 *
 **************************************************************/

using MediatR;
using Sgr.Application.Commands;
using Sgr.UPMS.Domain.Users;
using System.Threading;
using System.Threading.Tasks;

namespace Sgr.UPMS.Application.Commands.Users
{
    /// <summary>
    /// 修改用户状态命令处理器
    /// </summary>
    public class ModifyUserStatusCommandHandle : IRequestHandler<ModifyUserStatusCommand, CommandResult<bool>>
    {
        private readonly IUserRepository _userRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="userRepository">用户仓储</param>
        public ModifyUserStatusCommandHandle(IUserRepository userRepository)
        {
            _userRepository = userRepository;
        }

        /// <summary>
        /// 处理修改用户状态命令
        /// </summary>
        /// <param name="request">命令请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>处理结果</returns>
        public async Task<CommandResult<bool>> Handle(ModifyUserStatusCommand request, CancellationToken cancellationToken)
        {
            // 查找用户实体
            var user = await _userRepository.GetAsync(request.UserId, cancellationToken);

            // 如果找不到用户，返回NotFound结果
            if (user == null)
                return CommandResult.NotFound<bool>("未找到指定的用户");

            // 修改用户状态
            user.ChangeEntityStates(request.State);

            // 更新到仓储
            await _userRepository.UpdateAsync(user, cancellationToken);

            // 返回成功结果
            return CommandResult.Success(true, "用户状态修改成功");
        }
    }
}